package com.qs.user.ui.VM;

import android.app.Application;
import android.databinding.ObservableField;
import android.os.Build;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.qs.base.data.BaseData;
import com.qs.base.global.SPKeyGlobal;
import com.qs.base.router.RouterActivityPath;
import com.qs.base.utils.RetrofitClient;
import com.qs.user.api.ApiService;
import com.qs.user.entity.LoginEntity;
import com.qs.user.pay.util.GeneralUtils;
import com.qs.user.pay.util.MD5;
import com.qs.user.pay.util.TimeCountUtil;

import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by Walter on 2019/9/12.
 */

public class LoginViewModel extends BaseViewModel {

    private String code = "";
    private TimeCountUtil time;
    // 是否点击登录
    private boolean isLogin = true;
    // 验证码是否可以发送
    private boolean isCode = true;

    //手机号码
    public ObservableField<String> etphone = new ObservableField<>("");
    //手机验证码
    public ObservableField<String> etcode = new ObservableField<>("");
    // 获取验证码
    public ObservableField<String> vCode = new ObservableField<>("获取验证码");

    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {

    }

    public LoginViewModel(@NonNull Application application) {
        super(application);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (time != null) {
            time.cancel();
            time = null;
        }
    }

    //登录
    public BindingCommand toLogin = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            isLogin = true;
//            register("", etphone.get().toString(), "123456", etphone.get().toString());
            phoneLogin(etphone.get().toString(), "123456");
        }
    });

    //返回
    public BindingCommand finsh = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            finish();
        }
    });

    // 发送验证码
    public BindingCommand sendCode = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            sendCode(etphone.get().toString());
        }
    });

    // QQ登录
    public BindingCommand qqLogin = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            isLogin = false;
            txLogin();
        }
    });

    // 微信登录
    public BindingCommand wxLogin = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            isLogin = false;
            wxLogin();
        }
    });

    // 用户协议
    public BindingCommand agreement = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            ARouter.getInstance().build(RouterActivityPath.User.TreatyActivity).navigation();
        }
    });

    // 隐私政策
    public BindingCommand privacy = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            ARouter.getInstance().build(RouterActivityPath.User.AGREEMENT_ACTIVITY).navigation();
        }
    });


    /**
     * 登录
     *
     * @param imagePath
     * @param pwd
     * @param login
     * @param userName1
     */
    public void register(final String imagePath, final String login, String pwd, final String userName1) {

        String json = GeneralUtils.getJson(new String[]{"User_Name", "User_Phone", "User_Pwd"}, new String[]{StringUtils.isTrimEmpty(userName1) ? "" : userName1, login, pwd});
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .register(BaseData.APPNAME, body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        showDialog();
                    }
                })
                .subscribe(new Consumer<LoginEntity>() {
                    @Override
                    public void accept(LoginEntity loginEntity) throws Exception {
                        dismissDialog();
                        if ("SUCCESS".equals(loginEntity.getCreateState())) {
                            //注册成功，添加剩余数量
                            addNumbers(login, 10000 + "");
                        }
                        if ("SUCCESS".equals(loginEntity.getCreateState()) || "Account Exist".equals(loginEntity.getCreateState())) {
                            SPUtils.getInstance().put(SPKeyGlobal.USER_ID, login);
                            SPUtils.getInstance().put(SPKeyGlobal.USER_NAME, userName1);
                            SPUtils.getInstance().put(SPKeyGlobal.USER_IMG, imagePath);
                            ToastUtils.showShort("登录成功");
//                            userName.set(userName1);
//                            userImg.set(imagePath);
                            //请求翻译次数
                            getNumbersByUserid(login);
                            //请求会员信息
                            getVIPInfo(login);
                        } else {
                            ToastUtils.showShort("登录失败，请重试");
                        }

                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        //模拟成功
                        dismissDialog();
                        ToastUtils.showLong("请求超时...");
                    }
                });
    }

    public void phoneLogin(final String login, String pwd) {
        String json = GeneralUtils.getJson(new String[]{"client_id", "User_Phone", "User_Pwd"}, new String[]{Build.BRAND, login, MD5.MD532(pwd)});
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .phoneLogin(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        showDialog();
                    }
                })
                .subscribe(new Consumer<LoginEntity>() {
                    @Override
                    public void accept(LoginEntity loginEntity) throws Exception {
                        dismissDialog();

                        if (loginEntity != null && !TextUtils.isEmpty(loginEntity.getUser_Phone())) {
                            SPUtils.getInstance().put(SPKeyGlobal.USER_ID, login);
                            SPUtils.getInstance().put(SPKeyGlobal.USER_NAME, "");
                            SPUtils.getInstance().put(SPKeyGlobal.USER_IMG, "");
                            ToastUtils.showShort("登录成功");
//                            userName.set(userName1);
//                            userImg.set(imagePath);
                            //请求翻译次数
                            getNumbersByUserid(login);
                            //请求会员信息
                            getVIPInfo(login);
                        } else {
                            ToastUtils.showShort("登录失败，请使用第三方登录");
                        }


                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        //模拟成功
                        dismissDialog();
                        ToastUtils.showLong("请求超时...");
                    }
                });
    }

    // 发送验证码
    public void sendCode(String phone) {
        if (!isCode) {
            ToastUtils.showShort("验证码已经发送，请不要重复点击");
            return;
        }
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .code(BaseData.APPNAME, phone, MD5.MD532(phone))
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        showDialog();
                    }
                })
                .subscribe(new Consumer<LoginEntity>() {
                    @Override
                    public void accept(LoginEntity o) throws Exception {
                        dismissDialog();
                        if (!StringUtils.isEmpty(o.getMsg())) {
                            if (o.getMsg().contains("一天最多发5条")) {
                                ToastUtils.showShort(o.getMsg());
                                return;
                            }
                        }

                        code = o.getYzm();

                        time = new TimeCountUtil(60000, 1000);
                        time.setGetTime(new TimeCountUtil.getTime() {
                            @Override
                            public void onTick(long millisUntilFinished) {

                                isCode = false;
                                vCode.set("(" + millisUntilFinished / 1000 + ")秒后重发");
                            }

                            @Override
                            public void onFinish() {
                                isCode = true;
                                vCode.set("获取验证码");
                            }
                        });
//                        time.setBtnGetcode(tvCode);
                        time.start();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                        dismissDialog();
                    }
                });// 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
    }

    /**
     * 微信授权登录
     */
    public void wxLogin() {
        cn.sharesdk.framework.Platform plat = ShareSDK.getPlatform(Wechat.NAME);
        if (plat.isAuthValid())
            plat.removeAccount(true);
        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub
                arg2.printStackTrace();
                ToastUtils.showShort("Error");
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                //输出所有授权信息
                KLog.e(arg0.getDb().exportData());
                register(arg0.getDb().getUserIcon(), arg0.getDb().getUserId(), "", arg0.getDb().getUserName());
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub
                ToastUtils.showShort("取消");
            }
        });
        String userId = plat.getDb().getUserId();
        KLog.e(userId);
        plat.showUser(null);
    }

    /**
     * qq授权登录
     */
    public void txLogin() {
        Platform plat = ShareSDK.getPlatform(cn.sharesdk.tencent.qq.QQ.NAME);
        if (plat.isAuthValid())
            plat.removeAccount(true);
        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub
                arg2.printStackTrace();
                ToastUtils.showShort("Error");
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                //输出所有授权信息
                KLog.e(arg0.getDb().exportData());
                register(arg0.getDb().getUserIcon(), arg0.getDb().getUserId(), "", arg0.getDb().getUserName());
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub
                ToastUtils.showShort("取消");
            }
        });
        String userId = plat.getDb().getUserId();
        KLog.e(userId);
        //        plat.authorize();//授权不返回用户信息
        plat.showUser(null);//授权返回用户信息
    }


    /**
     * 剩余翻译次数
     *
     * @param userid
     */
    public void getNumbersByUserid(String userid) {

        Map<String, Object> map = new HashMap<>();
        map.put("userid", userid);
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .getNumbersByUserid(map)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                    }
                })
                .subscribe(new Consumer<Map<String, Object>>() {
                    @Override
                    public void accept(Map<String, Object> baseResult) throws Exception {
                        if (baseResult != null) {
                            String number = baseResult.get("numbers").toString();
                            if (StringUtils.isTrimEmpty(number))
                                SPUtils.getInstance().put(SPKeyGlobal.TRANSLATE_NUMBER, "0");
                            else
                                SPUtils.getInstance().put(SPKeyGlobal.TRANSLATE_NUMBER, number);

                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        ToastUtils.showLong("翻译剩余字数获取失败..");
                    }
                });
    }

    //会员剩余天数
    public void getVIPInfo(String userid) {

        Map<String, Object> map = new HashMap<>();
        map.put("appname", BaseData.payName);
        map.put("userphone", userid);
        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .getVIPInfo(map)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                    }
                })
                .subscribe(new Consumer<Map<String, Object>>() {
                    @Override
                    public void accept(Map<String, Object> baseResult) throws Exception {

                        if (baseResult != null) {
                            String day = baseResult.get("day").toString();
                            if (StringUtils.isTrimEmpty(day)) {
                                SPUtils.getInstance().put(SPKeyGlobal.USER_DATE, 0);
                            } else {
                                SPUtils.getInstance().put(SPKeyGlobal.USER_DATE, day);
                                if (!StringUtils.equals(day, "0")) {
                                    SPUtils.getInstance().put(SPKeyGlobal.USER_DATE, "无限制");
                                }
                            }
                        }
                        finish();
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                    }
                });
    }

    /**
     * 添加翻译次数
     *
     * @param userid
     * @param wordnumber
     */
    public void addNumbers(final String userid, String wordnumber) {

        Map<String, Object> map = new HashMap<>();
        map.put("userid", userid);
        map.put("wordnumber", wordnumber);
        Gson gson = new Gson();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson.toJson(map));

        RetrofitClient
                .getInstance()
                .create(ApiService.class)
                .addNumbers(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                    }
                })
                .subscribe(new Consumer<Map<String, Object>>() {
                    @Override
                    public void accept(Map<String, Object> baseResult) throws Exception {
                        dismissDialog();
                        if (baseResult != null && Integer.parseInt(baseResult.get("code").toString()) == 0) {
                            //请求翻译次数
                            getNumbersByUserid(userid);
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常
                        //模拟成功
                        dismissDialog();
                    }
                });
    }


}
